package main

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
)

func main() {
	// 要解密的 Token 字符串
	tokenString := "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ.p7HSX9f6ZnJ6jKxrIukdx7Yq3OW6shJVVnMvJYSKjI8J9AB--4Zlk4v1PPfhyEjK5JPtwJruyQHvOJdksW8gQ"

	// 将 PEM 格式的私钥解析为 ECDSA 私钥
	block, _ := pem.Decode([]byte(`-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIOs2dqzt1jIW0sRyFWdKLzw8NyTG/LMysXhA2dlLgbQJoAoGCCqGSM49
AwEHoUQDQgAErbVCg6vduYjLnkI/Lrr2UWbgMnudwaxj6/fHf6fc40/YWlL56GeJ
Nmn+32kZofwi8WxJ5E5+tTY/5FhsyjVXWg==
-----END EC PRIVATE KEY-----`))
	privateKey, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		fmt.Println("Error parsing ECDSA private key:", err)
		return
	}

	//// 从私钥中提取公钥信息
	//publicKey := privateKey.Public()

	// 解密 Token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return &privateKey.PublicKey, nil
	})
	if err != nil {
		fmt.Println("Error parsing JWT token:", err)
		return
	}

	// 验证 Token
	if !token.Valid {
		fmt.Println("Invalid JWT token")
		return
	}

	// 获取 Token 的声明（payload）
	claims := token.Claims.(jwt.MapClaims)
	fmt.Println("Name:", claims["name"])
	fmt.Println("Is admin:", claims["admin"])
	fmt.Println("Issued at:", claims["iat"])
}
